<template>
  <div class="customer-review-page">
    <div class="page-header">
      <h2>客户审核</h2>
      <el-button type="primary" @click="handleRefresh">
        <el-icon><Refresh /></el-icon>
        刷新
      </el-button>
    </div>

    <!-- 搜索筛选 -->
    <el-card class="filter-card" shadow="never">
      <el-form :model="filterForm" inline>
        <el-form-item label="审核类别">
          <el-select
            v-model="filterForm.review_type"
            placeholder="请选择"
            clearable
            style="width: 150px"
          >
            <el-option label="客户审核" value="customer" />
            <el-option label="联系人审核" value="contact" />
          </el-select>
        </el-form-item>
        <el-form-item label="审核状态">
          <el-select
            v-model="filterForm.status"
            placeholder="请选择"
            clearable
            style="width: 150px"
          >
            <el-option label="待审核" :value="1" />
            <el-option label="审核通过" :value="2" />
            <el-option label="审核驳回" :value="3" />
          </el-select>
        </el-form-item>
        <el-form-item label="关键词">
          <el-input
            v-model="filterForm.keyword"
            placeholder="客户名称/联系人"
            clearable
            style="width: 200px"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 统计卡片 -->
    <el-row :gutter="16" class="stats-row">
      <el-col :span="6">
        <el-card shadow="hover">
          <div class="stat-item">
            <div class="stat-label">待审核</div>
            <div class="stat-value pending">
              {{ stats.customer.pending + stats.contact.pending }}
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card shadow="hover">
          <div class="stat-item">
            <div class="stat-label">已通过</div>
            <div class="stat-value approved">
              {{ stats.customer.approved + stats.contact.approved }}
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card shadow="hover">
          <div class="stat-item">
            <div class="stat-label">已驳回</div>
            <div class="stat-value rejected">
              {{ stats.customer.rejected + stats.contact.rejected }}
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card shadow="hover">
          <div class="stat-item">
            <div class="stat-label">总计</div>
            <div class="stat-value">{{ stats.customer.total + stats.contact.total }}</div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 数据表格 -->
    <el-card class="table-card" shadow="never">
      <el-table :data="tableData" v-loading="loading" stripe>
        <el-table-column prop="id" label="ID" width="60" />
        <el-table-column prop="category" label="审核类别" width="100">
          <template #default="{ row }">
            <el-tag :type="row.category === 'customer' ? 'primary' : 'success'">
              {{ row.category === 'customer' ? '客户审核' : '联系人审核' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="customer_name" label="客户名称" min-width="150" />
        <el-table-column prop="legal_person" label="法人" min-width="120" show-overflow-tooltip>
          <template #default="{ row }">
            <span v-if="row.category === 'customer'">{{ row.legal_person || '-' }}</span>
            <span v-else>{{ row.contact_name || '-' }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="review_type_text" label="操作类型" width="100" />
        <el-table-column prop="user_name" label="申请人" width="100" />
        <el-table-column prop="status" label="审核状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getStatusType(row.status)">
              {{ getStatusText(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="create_time" label="提交时间" width="160" />
        <el-table-column label="操作" width="120" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" link @click="handleDetail(row)">查看详情</el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination">
        <el-pagination
          v-model:current-page="pagination.current"
          v-model:page-size="pagination.size"
          :total="pagination.total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 审核详情抽屉 -->
    <GlobalDrawer v-model="detailVisible" title="审核详情" size="80%" :show-footer-buttons="false">
      <div v-if="currentReview" v-loading="detailLoading">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="审核类别">
            {{ currentReview.category === 'customer' ? '客户审核' : '联系人审核' }}
          </el-descriptions-item>
          <el-descriptions-item label="操作类型">
            {{ currentReview.review_type_text }}
          </el-descriptions-item>
          <el-descriptions-item label="客户名称">
            {{ currentReview.customer_name }}
          </el-descriptions-item>
          <el-descriptions-item
            label="法人"
            v-if="currentReview.category === 'customer' && currentReview.legal_person"
          >
            {{ currentReview.legal_person }}
          </el-descriptions-item>
          <el-descriptions-item
            label="联系人"
            v-if="currentReview.category === 'contact' && currentReview.contact_name"
          >
            {{ currentReview.contact_name }}
          </el-descriptions-item>
          <el-descriptions-item label="申请人">
            {{ currentReview.user_name }}
          </el-descriptions-item>
          <el-descriptions-item label="提交时间">
            {{ currentReview.create_time }}
          </el-descriptions-item>
          <el-descriptions-item label="审核状态">
            <el-tag :type="getStatusType(currentReview.status)">
              {{ getStatusText(currentReview.status) }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="审核人" v-if="currentReview.reviewer_name">
            {{ currentReview.reviewer_name }}
          </el-descriptions-item>
          <el-descriptions-item label="审核时间" v-if="currentReview.review_time">
            {{ currentReview.review_time }}
          </el-descriptions-item>
        </el-descriptions>

        <div class="data-compare" style="margin-top: 20px">
          <h4>变更内容对比</h4>
          <el-row :gutter="20">
            <el-col :span="12" v-if="currentReview.review_type !== 1">
              <div class="compare-card">
                <h5>原始数据</h5>
                <pre>{{ formatJson(currentReview.original_data) }}</pre>
              </div>
            </el-col>
            <el-col :span="currentReview.review_type !== 1 ? 12 : 24">
              <div class="compare-card">
                <h5>
                  {{
                    currentReview.review_type === 1
                      ? '新增数据'
                      : currentReview.review_type === 2
                        ? '修改后数据'
                        : '删除数据'
                  }}
                </h5>
                <pre>{{
                  formatJson(
                    currentReview.review_type === 3
                      ? currentReview.original_data
                      : currentReview.new_data
                  )
                }}</pre>
              </div>
            </el-col>
          </el-row>
        </div>

        <div v-if="currentReview.review_remark" style="margin-top: 20px">
          <h4>审核备注</h4>
          <p>{{ currentReview.review_remark }}</p>
        </div>

        <!-- 审核操作区 -->
        <div
          v-if="currentReview.status === 1"
          class="approve-actions"
          style="margin-top: 30px; padding-top: 20px; border-top: 1px solid #e4e7ed"
        >
          <h4>审核操作</h4>
          <el-form :model="approveForm" label-width="80px" style="margin-top: 15px">
            <el-form-item label="审核备注">
              <el-input
                v-model="approveForm.remark"
                type="textarea"
                :rows="4"
                placeholder="请输入审核备注"
              />
            </el-form-item>
            <el-form-item>
              <el-button type="success" @click="handleApproveInDrawer(2)" :loading="submitting">
                <el-icon><Select /></el-icon>
                审核通过
              </el-button>
              <el-button type="danger" @click="handleApproveInDrawer(3)" :loading="submitting">
                <el-icon><CloseBold /></el-icon>
                审核驳回
              </el-button>
              <el-button @click="detailVisible = false">取消</el-button>
            </el-form-item>
          </el-form>
        </div>
      </div>
    </GlobalDrawer>
  </div>
</template>

<script setup lang="ts">
  import { ref, reactive, onMounted } from 'vue'
  import { ElMessage, ElMessageBox } from 'element-plus'
  import GlobalDrawer from '@/components/common/GlobalDrawer.vue'
  import { Refresh, Select, CloseBold } from '@element-plus/icons-vue'
  import { customerReviewApi } from '@/api/crm.ts'

  const loading = ref(false)
  const detailLoading = ref(false)
  const submitting = ref(false)
  const tableData = ref<any[]>([])
  const detailVisible = ref(false)
  const currentReview = ref<any>(null)

  const filterForm = reactive<{
    review_type: string | number
    status: string | number
    keyword: string
  }>({
    review_type: '',
    status: '',
    keyword: '',
  })

  const pagination = reactive({
    current: 1,
    size: 20,
    total: 0,
  })

  const approveForm = reactive({
    remark: '',
  })

  const stats = ref({
    customer: {
      pending: 0,
      approved: 0,
      rejected: 0,
      total: 0,
    },
    contact: {
      pending: 0,
      approved: 0,
      rejected: 0,
      total: 0,
    },
  })

  // 获取审核列表
  const getReviewList = async () => {
    loading.value = true
    try {
      const params = {
        page: pagination.current,
        limit: pagination.size,
        review_type: filterForm.review_type || undefined,
        status: filterForm.status ? Number(filterForm.status) : undefined,
        keyword: filterForm.keyword || undefined,
      }
      const res = await customerReviewApi.list(params)

      tableData.value = res.data.list || []
      pagination.total = res.data.total || 0
    } catch (error) {
      console.error('获取审核列表失败:', error)
      ElMessage.error('获取审核列表失败')
    } finally {
      loading.value = false
    }
  }

  // 获取统计信息
  const getStatistics = async () => {
    try {
      const res = await customerReviewApi.statistics()
      stats.value = res.data
    } catch (error) {
      console.error('获取统计信息失败:', error)
    }
  }

  // 获取状态类型
  const getStatusType = (status: number) => {
    const types: Record<number, string> = {
      1: 'warning',
      2: 'success',
      3: 'danger',
    }
    return types[status] || 'info'
  }

  // 获取状态文本
  const getStatusText = (status: number) => {
    const texts: Record<number, string> = {
      1: '待审核',
      2: '审核通过',
      3: '审核驳回',
    }
    return texts[status] || '未知'
  }

  // 格式化JSON
  const formatJson = (jsonStr: string | object) => {
    try {
      const obj = typeof jsonStr === 'string' ? JSON.parse(jsonStr) : jsonStr
      return JSON.stringify(obj, null, 2)
    } catch (error) {
      return jsonStr
    }
  }

  // 查看详情
  const handleDetail = async (row: any) => {
    detailLoading.value = true
    detailVisible.value = true
    approveForm.remark = ''

    try {
      console.log('调用API参数:', row.id, row.category)
      const res = await customerReviewApi.detail(row.id, row.category)
      console.log('API响应:', res)
      currentReview.value = res.data
    } catch (error: any) {
      console.error('获取详情失败:', error)
      ElMessage.error(error.message || '获取详情失败')
      detailVisible.value = false
    } finally {
      detailLoading.value = false
    }
  }

  // 在抽屉中进行审核
  const handleApproveInDrawer = async (status: number) => {
    const action = status === 2 ? '通过' : '驳回'

    try {
      await ElMessageBox.confirm(`确认审核${action}该申请吗？`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })

      submitting.value = true
      await customerReviewApi.approve({
        id: currentReview.value.id,
        category: currentReview.value.category,
        status: status,
        remark: approveForm.remark,
      })

      ElMessage.success(`审核${action}成功`)
      detailVisible.value = false
      getReviewList()
      getStatistics()
    } catch (error: any) {
      if (error !== 'cancel') {
        console.error('审核失败:', error)
        ElMessage.error(error.message || '审核失败')
      }
    } finally {
      submitting.value = false
    }
  }

  // 搜索
  const handleSearch = () => {
    pagination.current = 1
    getReviewList()
  }

  // 重置
  const handleReset = () => {
    filterForm.review_type = ''
    filterForm.status = ''
    filterForm.keyword = ''
    pagination.current = 1
    getReviewList()
  }

  // 刷新
  const handleRefresh = () => {
    getReviewList()
    getStatistics()
  }

  // 分页大小改变
  const handleSizeChange = (size: number) => {
    pagination.size = size
    pagination.current = 1
    getReviewList()
  }

  // 当前页改变
  const handleCurrentChange = (current: number) => {
    pagination.current = current
    getReviewList()
  }

  onMounted(() => {
    getReviewList()
    getStatistics()
  })
</script>

<style scoped>
  .customer-review-page {
    padding: 20px;
  }

  .page-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
  }

  .page-header h2 {
    margin: 0;
    font-size: 20px;
    font-weight: 500;
  }

  .filter-card {
    margin-bottom: 16px;
  }

  .stats-row {
    margin-bottom: 16px;
  }

  .stat-item {
    text-align: center;
  }

  .stat-label {
    font-size: 14px;
    color: #909399;
    margin-bottom: 8px;
  }

  .stat-value {
    font-size: 28px;
    font-weight: bold;
    color: #303133;
  }

  .stat-value.pending {
    color: #e6a23c;
  }

  .stat-value.approved {
    color: #67c23a;
  }

  .stat-value.rejected {
    color: #f56c6c;
  }

  .pagination {
    margin-top: 20px;
    text-align: right;
  }

  .data-compare h4 {
    margin-bottom: 16px;
    color: #303133;
  }

  .compare-card {
    padding: 15px;
    background: #f5f7fa;
    border-radius: 4px;
  }

  .compare-card h5 {
    margin: 0 0 10px 0;
    color: #606266;
  }

  .compare-card pre {
    margin: 0;
    padding: 10px;
    background: #fff;
    border-radius: 4px;
    overflow-x: auto;
    font-size: 12px;
    line-height: 1.5;
  }
</style>
